from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView, GenericAPIView
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from rest_framework import status
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import CreateModelMixin, UpdateModelMixin, ListModelMixin
from django_redis import get_redis_connection
from rest_framework_jwt.views import ObtainJSONWebToken

from users.models import User
from . import constants
from .serializers import UserAddressSerializer, CreateUserSerializer, UserDetailSerializer, EmailSerializer, AddressTitleSerializer
from . import serializers
from goods.models import SKU
from goods.serializers import SKUSerializer
from carts.utils import merge_cart_cookie_to_redis


# Create your views here.


# 校验用户是否已存在
# GET usernames/(?P<username>\w{5,20})/count/
class UsernameCountView(APIView):
    def get(self, request, username):
        count = User.objects.filter(username=username).count()
        data = {
            "username": username,
            "count": count
        }
        return Response(data)

# 校验手机号是否已存在
# mobiles/(?P<mobile>1[3-9]\d{9})/count
class MobileCountView(APIView):
    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()

        data = {
            'mobile': mobile,
            'count': count
        }
        return Response(data)

# 用户注册
class UserView(CreateAPIView):
    serializer_class = CreateUserSerializer

    # 尝试实现物车合并, 失败
    # def post(self, request, *args, **kwargs):
    #     super(UserView, self).post(request, *args, **kwargs)
    #     response = self.create(request, *args, **kwargs)
    #     user = self.get_serializer(data=request.data).save()
    #     merge_cart_cookie_to_redis(request=request, response=response, user=user)
    #     return response


# 用户个人信息展示
class UserDetailView(RetrieveAPIView):

    serializer_class = UserDetailSerializer

    permission_classes = [IsAuthenticated]

    def get_object(self):
        return self.request.user

#添加邮箱
class EmailView(UpdateAPIView):

    permission_classes = [IsAuthenticated]
    serializer_class = EmailSerializer

    def get_object(self):
        return self.request.user

# 激活验证邮箱
class VerifyEmailView(APIView):

    def get(self, request):
        token = request.query_params.get('token')
        if not token:
            return Response({'message': '缺少token'}, status=status.HTTP_400_BAD_REQUEST)

        user = User.check_verify_email_url(token)
        if not user:
            return Response({'message': '链接信息失效'}, status=status.HTTP_400_BAD_REQUEST)
        else:
            user.email_active = True
            user.save()
            return Response({'message': '验证成功'})

# 用户地址管理
class AddressViewSet(CreateModelMixin, UpdateModelMixin, GenericViewSet):
    serializer_class = UserAddressSerializer
    permission = [IsAuthenticated]
    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    def list(self, request, *args, **kwargs):
        '''用户地址列表数据'''
        # print('111111111')
        queryset = self.get_queryset()
        serializers = self.get_serializer(queryset, many=True)
        user = self.request.user
        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address_id,
            'limit': constants.USER_ADDRESS_COUNTS_LIMIT,
            'addresses': serializers.data,
        })
    def create(self, request, *args, **kwargs):
        '''保存用户地址数据'''
        # 检测用户地址数目, 不能超过上线
        count = request.user.addresses.count()
        if count >= constants.USER_ADDRESS_COUNTS_LIMIT:
            return Response({'message': '保存地址数据超出上线'}, status=status.HTTP_400_BAD_REQUEST)
        return super().create(request, *args, **kwargs)

    def destroy(self, request, *args, **kwargs):
        '''处理删除'''
        address = self.get_object()
        address.is_deleted = True
        address.save()
        return Response(status=status.HTTP_204_NO_CONTENT)

    # detail为False 表示不需要处理具体的对象不使用URL获取主键
    # True表示使用通过URL获取的主键对应的数据对象
    # 添加自定义动作需要使用rest_framework.decorators.action装饰器。
    #
    @action(methods=['put'], detail=True)
    def status(self, request, pk=None, address_id=None):
        '''设置默认地址'''
        address = self.get_object()
        request.user.default_address = address
        request.user.save()
        return Response({'message': 'ok'}, status=status.HTTP_200_OK)
    @action(methods=['put'], detail=True)
    def title(self, request, pk=None, address_id=None):
        '''修改标题'''
        address = self.get_object()
        serializer = AddressTitleSerializer(instance=address, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)

# 用户浏览记录
class UserBrowsingHistoryView(CreateModelMixin, GenericAPIView):
    '''
    用户浏览记录
    '''

    permission_classes = [IsAuthenticated]
    serializer_class = serializers.AddUserBrowsingHistorySerializer

    def post(self, request):
        return self.create(request)

    def get(self, request):
        user_id = request.user.id
        redis_coon = get_redis_connection('history')
        history = redis_coon.lrange("history_%s" % user_id, 0, constants.USER_BROWSING_HISTORY_COUNTS_LIMIT-1)
        skus = []
        for sku_id in history:
            sku = SKU.objects.get(id=sku_id)
            skus.append(sku)

        serializer = SKUSerializer(skus, many=True)
        data = serializer.data
        return Response(data)

# 用户登录
class UserAuthorizeView(ObtainJSONWebToken):
    def post(self, request, *args, **kwargs):
        response = super(UserAuthorizeView, self).post(request, *args, **kwargs)


        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            user = serializer.object.get('user') or request.user
            response = merge_cart_cookie_to_redis(request=request, user=user, response=response)

        return response





